package org.smarthings.impl;

import java.util.ArrayList;
import java.util.List;

import org.smarthings.Factory;
import org.smarthings.Message;
import org.smarthings.MessageBroker;
import org.smarthings.Response;
import org.smarthings.Server;

public class MessageBrokerImpl extends MessageBroker {
	private static MessageBrokerImpl instance = new MessageBrokerImpl();
	public static MessageBroker backend = HttpBrokerImpl.getInstance();
	private List<Server> servers = new ArrayList<Server>();
	private List<String> duplicates = new ArrayList<String>();

	private MessageBrokerImpl() {
		super();
	}

	public static MessageBrokerImpl getInstance() {
		return instance;
	}

	public synchronized void addFactory(Factory factory) {
		servers.add(factory.startNewServer());
	}

	public synchronized void removeFactory(Factory factory) {
		for (Server server : servers) {
			if (factory.getProtocol().equals(server.getProtocol())) {
				server.stop();
				return;
			}
		}
	}

	public synchronized void stop() {
		for (Server server : servers) {
			server.stop();
		}
		servers.clear();
		duplicates.clear();
	}

	public Message get(String uri, String contentType) {
		return backend.get(uri, contentType);
	}

	public Response post(Message message) {
		duplicates.add(message.getUri());
		Response response = backend.post(message);
		broadcast(message.getUri(), message.getProtocol());
		return response;
	}

	public void update(String uri) {
		if (!duplicates.remove(uri)) {
			broadcast(uri, PROTOCOL);
		}
	}

	private void broadcast(final String uri, final String origProtocol) {
		new Thread() {
			public void run() {
				for (Server server : servers) {
					if (!origProtocol.equalsIgnoreCase(server.getProtocol())) {
						server.update(uri);
					}
				}
			};
		}.start();
	}
}
